﻿//-----------------------------------------------------------------------
// <copyright file="RemoveUpdateFolderStage.cs" author="Artak Mkrtchyan">
//     Creative Commons - GNU General Public License (http://creativecommons.org/licenses/GPL/2.0/
// </copyright>
// <author>Artak Mkrtchyan</author>
// <email>mkArtak@gmail.com</email>
// <date>20/03/2013</date>

using ConsoleHoster.Common.Utilities;
using ConsoleHoster.Common.Utilities.IO;
using System;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;

namespace AppUpdateInstaller.Model.InstallationStages
{
	internal sealed class RemoveUpdateFolderStage : InstallationStageBase
	{
		private readonly string appUpdateFolder;
		private readonly string binariesFolder;

		public RemoveUpdateFolderStage(string argUpdateFolder, string argBinariesFolder, IFileSystemContentProvider argFileSystemContentProvider, IProcessManager argProcessManager, Action argShutdownLogic)
			: base(argProcessManager, argFileSystemContentProvider, argShutdownLogic)
		{
			if (!this.FileSystemContentProvider.DirectoryExists(argUpdateFolder))
			{
				throw new ArgumentException("The specified update folder does not exist");
			}

			if (this.FileSystemContentProvider.GetCurrentDirectory().Equals(argUpdateFolder, StringComparison.InvariantCultureIgnoreCase))
			{
				throw new ArgumentException("The stage cannot run under this mode");
			}

			if (!this.FileSystemContentProvider.DirectoryExists(argBinariesFolder))
			{
				throw new DirectoryNotFoundException("Invalid binaries directory specified");
			}

			this.appUpdateFolder = argUpdateFolder;
			this.binariesFolder = argBinariesFolder;
		}

		public override void Run()
		{
			this.NotifyProgressChange(new InstallationStageProgressEventArgs { Status = "Removing update sources..." });

			this.FileSystemContentProvider.DeleteDirectory(this.appUpdateFolder, true);
		}

		public override void FinalizeStage()
		{
			using (Process tmpProcess = this.ProcessManager.StartProcess(Path.Combine(this.binariesFolder, "ConsoleHoster.exe")))
			{
				tmpProcess.WaitForInputIdle();
			}

			if (this.ShutdownAction != null)
			{
				this.ShutdownAction();
			}
		}

		public override bool HasFinalizerStage
		{
			get
			{
				return true;
			}
		}
	}
}
